﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace RecursiveFileSearch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();

            tbStartingFolder.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var result = Search(tbStartingFolder.Text, tbExtensions.Text, tbSearchFor.Text);

            //var x = result.Count();
            var foundFiles = result.ToList();

            StringBuilder oSb = new StringBuilder();
            foundFiles.ForEach(f =>
            {
                oSb.Append(f + "\r\n");
            });

            tbResults.Text = oSb.ToString();
        }

        static IEnumerable<string> Search(string root, string fileNameSearchPattern, string textSearchPattern)
        {
            Queue<string> dirs = new Queue<string>();
            dirs.Enqueue(root);
            while (dirs.Count > 0)
            {
                string dir = dirs.Dequeue();

                // files
                string[] paths = null;
                try
                {
                    paths = Directory.GetFiles(dir, fileNameSearchPattern);
                }
                catch { } // swallow

                if (paths != null && paths.Length > 0)
                {
                    foreach (string file in paths)
                    {
                        string fileContents;

                        using (TextReader reader = File.OpenText(file))
                        {
                            fileContents = reader.ReadToEnd();
                        }

                        if (fileContents.Contains(textSearchPattern))
                        {
                            yield return file;
                        }
                    }
                }

                // sub-directories
                paths = null;
                try
                {
                    paths = Directory.GetDirectories(dir);
                }
                catch { } // swallow

                if (paths != null && paths.Length > 0)
                {
                    foreach (string subDir in paths)
                    {
                        dirs.Enqueue(subDir);
                    }
                }
            }
        }



    }
}
